<template>
  <section>
    <!--工具条-->
    <toolbar :buttonList="buttonList" @callFunction="callFunction"></toolbar>

    <el-table
      :data="tableData"
      style="width: 100%"
      row-key="ID"
      border
      ref="mytable"
    default-expand-all
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      :tree-props="{ children: 'Children', hasChildren: 'HasChildren' }"
      @row-click="clickRow"
    >
      <el-table-column type="selection" width="50"> </el-table-column>
      <el-table-column prop="Name" label="类别" sortable width="300">
      </el-table-column>

      <el-table-column
        prop="InsertTime"
        label="添加日期"
        :formatter="formatCreateTime"
        sortable
        width="200"
      >
      </el-table-column>
      <el-table-column prop="Sequence" label="排序"> </el-table-column>
      <el-table-column prop="Path" label="地址"> </el-table-column>
      <el-table-column label="关闭状态">
        <template slot-scope="scope">
          <el-tag
            :type="!scope.row.IsEnabled ? 'success' : 'danger'"
            disable-transitions
            >{{ !scope.row.IsEnabled ? "是" :  "否" }}</el-tag
          >
        </template>
      </el-table-column>
    </el-table>
    <!--新增界面-->
    <el-dialog
      title="新增"
      :visible.sync="addFormVisible"
      v-model="addFormVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="addForm"
        label-width="80px"
        :rules="addFormRules"
        ref="addFormRef"
      >
        <el-form-item label="菜单名称" prop="Name">
          <el-input v-model="addForm.Name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="序号" prop="Sequence">
          <el-input v-model="addForm.Sequence" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="父级菜单" prop="pidArray">
          <el-cascader
            :options="tableData"
            v-model="pidArray"
            style="width: 100%"
            size="mini"
            :props="{children: 'Children', hasChildren: 'HasChildren', checkStrictly: true, value: 'ID', label: 'Name' }"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="状态" prop="IsEnabled">
          <el-select v-model="addForm.IsEnabled" placeholder="请选择状态">
            <el-option label="禁用" :value="false"></el-option>
            <el-option label="启用" :value="true"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click.native="saveSubmit"
          :loading="addLoading"
          >提交</el-button
        >
      </div>
    </el-dialog>
    <!--工具条-->
    <el-col :span="24" class="toolbar"> </el-col>
  </section>
</template>

<script>
import util from "../../../util/date";
import { getCategoryList, saveCategory, removeCategory } from "../../api/api";
import { getButtonList } from "../../promissionRouter";
import Toolbar from "../../components/Toolbar";
import qs from "qs";
export default {
  components: { Toolbar },
  data() {
    return {
      buttonList: [],
      currentRow: null,
      tableData: [],
      dialogVisible: false,
      select: {},
      addFormRules: {
        Name: [{ required: true, message: "请填写类别名称", trigger: "blur" }],
      },
      pidArray: [],
      loading: false,
      addDialogFormVisible: false,
      addFormVisible: false, //新增界面是否显示
      addLoading: false,
      addForm: {
        Name: "",
        IsEnabled: true,
        Pid: "",
        Sequence: 0,
        RootID: ""
      },
    };
  },
  methods: {
    clickRow: function (row) {
      this.select = row;
      this.$refs.mytable.clearSelection();
      this.$refs.mytable.toggleRowSelection(row);
    },
    callFunction(item) {
      this.filters = {
        name: item.search,
      };
      if(item.Func=='search')
      {
        this.page.PageIndex=1;
      }
      this[item.Func].apply(this, item);
    },
    //获取用户列表
    search() {
      this.loading = true;
      let param={pid:"0",isRoot:true};
      getCategoryList(param).then((res) => {
        this.tableData = res.Data;
        this.loading = false;
        console.log(this.tableData);
      });
    },
    formatCreateTime: function (row, column) {
      return !row.InsertTime || row.InsertTime == ""
        ? ""
        : util.formatDate.format(new Date(row.InsertTime), "yyyy-MM-dd");
    },
    //删除
    remove() {
      var rows = this.$refs.mytable.selection;
      if (rows.length == 0) {
        this.$message({
          message: "请选择要删除的数据！",
          type: "error",
        });
        return;
      }
      var arrayIds = [];
      var arrayNames = [];
      rows.map((c) => {
        arrayIds.push(c.id);
        arrayNames.push(c.name);
        return c.id;
      });

      this.$confirm("确认删除【" + arrayNames + "】吗?", "提示", {
        type: "warning",
      })
        .then(() => {
          this.listLoading = true;
          let param = qs.stringify({ ids: arrayIds });
          //let param = { ids: arrayIds };
          removeCategory(param).then((res) => {
            if (util.isEmt.format(res)) {
              this.listLoading = false;
              return;
            }
            this.listLoading = false;
            if (res.data.isSuccess) {
              this.$message({
                message: "删除成功",
                type: "success",
              });
            } else {
              this.$message({
                message: res.data.message,
                type: "error",
              });
            }

            this.search();
          });
        })
        .catch(() => {});
    },
    //显示编辑界面
    update() {
      if (!this.select.hasOwnProperty("ID")) {
        this.$message({
          message: "请选择要编辑的一行数据！",
          type: "error",
        });

        return;
      }
      this.pidArray=[];
      this.addFormVisible = true;
      this.addForm = Object.assign({}, this.select);
      if(!util.isEmt.format(this.addForm.PidArray))
      {
      this.pidArray=this.addForm.PidArray.toString().split(',');
      }
    },
    //显示新增界面
    insert() {
      this.addFormVisible = true;
      this.addForm = Object.assign({}, {});
    },
    //新增
    saveSubmit: function () {
      let _this = this;
      this.$refs.addFormRef.validate((valid) => {
        if (valid) {
          this.addLoading = true;
          let param = Object.assign({}, this.addForm);
          if(this.pidArray.length==0)
          {
              this.$message({
                message: "请选择父级目录",
                type: "success",
              });
              return ;

          }
          if (this.pidArray.length == 1) {
            param.rootID = "0";
          } else {
            param.rootID = this.pidArray[0];
          }
          param.pid = this.pidArray[this.pidArray.length - 1];
          param.pidArray = this.pidArray.join(",");
          saveCategory(param).then((res) => {
            if (res.data.IsSuccess) {
              this.addLoading = false;
                this.addFormVisible = false;
              this.$message({
                message: res.data.Message,
                type: "success",
              });
              this.$refs["addFormRef"].resetFields();
            
              this.search();
            } else {
              this.$message({
                message: res.data.Message,
                type: "error",
              });
            }
          });
        }
      });
    },
  },
  mounted() {
    this.search();

    let routers = window.localStorage.router
      ? JSON.parse(window.localStorage.router)
      : [];
    this.buttonList = getButtonList(this.$route.path, routers);
  },
};
</script>

<style scoped>
</style>
